package com.heimali.happyreader.config;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import com.heimali.happyreader.model.Array;
import com.heimali.happyreader.model.KVPair;

import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public abstract class BaseConfig {
	abstract protected String getSPKey();

	abstract protected SharedPreferences getSP();

	private static final String DEFAULT_VALUE = "";

	protected BaseConfig() {
	}

	public void setConfig(String key, Boolean value) {
		setConfig(key, value ? "true" : "false");
	}

	public void setConfig(String key, String value) {
		Editor edit = getSP().edit();
		edit.putString(key, value);
		edit.commit();
	}

	public void setConfig(Map<String, String> map) {
		Editor edit = getSP().edit();

		Set<Map.Entry<String, String>> set = map.entrySet();
		Iterator<Map.Entry<String, String>> it = set.iterator();
		while (it.hasNext()) {
			Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
			edit.putString(entry.getKey(), entry.getValue());
		}

		edit.commit();
	}

	public void setConfig(Array array) {
		Editor edit = getSP().edit();

		for (int size = array.size(), i = 0; i < size; i++) {
			@SuppressWarnings("unchecked")
			KVPair<String, String> item = (KVPair<String, String>) array.get(i);
			edit.putString(item.getKey(), item.getValue());
		}

		edit.commit();
	}

	public String getConfig(String key) {
		return getConfig(key, DEFAULT_VALUE);
	}

	public String getConfig(String key, String defaultValue) {
		if (defaultValue == null) {
			defaultValue = DEFAULT_VALUE;
		}
		return getSP().getString(key, defaultValue);
	}

	public Boolean getConfig(String key, Boolean defaultValue) {
		String res = getConfig(key);
		return (res == DEFAULT_VALUE) ? defaultValue : ("true".equals(res));
	}

}
